import type { ListByUserMessageType, MessageTargetParams, MessageTargetType } from './model'
import { getMessageTargetsAPI } from './api'
import type { SpColumnsType } from '@/components/SpTable/type'
import { Avatar, Tag } from 'ant-design-vue'
import { formatFileUrl } from '@/utils/fileUtils'

export function useDetail(data: ListByUserMessageType) {
  const columns: SpColumnsType[] = [
    {
      title: '用户头像',
      dataIndex: 'avatar',
      width: 100,
      align: 'center',
      cellRenderer: (record: MessageTargetType) => {
        return <Avatar src={formatFileUrl(record.avatar)} size={50} />
      }
    },
    {
      title: '用户名',
      dataIndex: 'username',
      width: 100,
      align: 'center'
    },
    {
      title: '状态',
      dataIndex: 'status',
      cellRenderer: (record: MessageTargetType) => {
        if (record.isRead) {
          return <Tag color="green">已读</Tag>
        } else {
          return <Tag color="red">未读</Tag>
        }
      },
      width: 100,
      align: 'center'
    },
    {
      title: '阅读时间',
      dataIndex: 'readTime',
      width: 120,
      align: 'center'
    }
  ]

  // 阅读情况抽屉
  const open = ref<boolean>(false)
  // 阅读情况列表
  const messageTargets = ref<MessageTargetType[]>([])
  // loading
  const messageTargetsLoading = ref<boolean>(false)
  // 阅读情况列表参数
  const messageTargetsParams = ref<MessageTargetParams>({
    pageNum: 1,
    pageSize: 10,
    total: 0
  })
  const afterOpenChange = (bool: boolean) => {
    bool && getMessageTargets()
  }
  // 获取阅读情况列表
  function getMessageTargets() {
    messageTargetsLoading.value = true
    getMessageTargetsAPI(data.id, messageTargetsParams.value)
      .then((res) => {
        messageTargets.value = res.data.rows
        messageTargetsParams.value.total = res.data.total
      })
      .finally(() => {
        messageTargetsLoading.value = false
      })
  }

  // 分页
  function paginationChange(paging: number, size: number) {
    messageTargetsParams.value.pageNum = paging
    messageTargetsParams.value.pageSize = size
    getMessageTargets()
  }

  // 清空
  function clear() {
    messageTargetsParams.value = Object.assign({
      pageNum: 1,
      pageSize: 5
    })
    getMessageTargets()
  }

  // 搜索
  function search() {
    messageTargetsParams.value.pageNum = 1
    getMessageTargets()
  }

  return {
    open,
    messageTargets,
    messageTargetsLoading,
    messageTargetsParams,
    columns,
    afterOpenChange,
    paginationChange,
    clear,
    search
  }
}
